package com.example.electricbicycle.controller;

import com.example.electricbicycle.po.AfterSalesAdmin;
import com.example.electricbicycle.service.AfterSalesAdminService;
import com.example.electricbicycle.service.AfterSalesAdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@WebServlet("/afterSalesAdmin")
public class AfterSalesAdminServlet extends HttpServlet {
    private final AfterSalesAdminService afterSalesService = new AfterSalesAdminServiceImpl();
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out=response.getWriter();
        String action = request.getParameter("action");

        if ("list".equals(action) || action == null) {
            // 查询所有售后订单或按ID查询
            String id = request.getParameter("id");
            if (id != null) {
                AfterSalesAdmin afterSales = afterSalesService.getAfterSalesById(Integer.parseInt(id));
                List<AfterSalesAdmin> list = (afterSales != null) ? Arrays.asList(afterSales) : new ArrayList<>();
                request.setAttribute("afterSalesList", list);
            } else {
                List<AfterSalesAdmin> afterSalesList = afterSalesService.getAllAfterSales();
                request.setAttribute("afterSalesList", afterSalesList);
            }
            request.getRequestDispatcher("/aftersalesadmin/aftersaleslist.jsp").forward(request, response);

        } else if ("addForm".equals(action)) {
            // 跳转到添加售后订单页面
            request.getRequestDispatcher("/aftersalesadmin/addaftersale.jsp").forward(request, response);

        } else if ("editForm".equals(action)) {
            // 跳转到编辑售后订单页面
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                AfterSalesAdmin afterSales = afterSalesService.getAfterSalesById(id);
                if (afterSales != null) {
                    request.setAttribute("afterSales", afterSales);
                    request.setAttribute("createTimeStr", sdf.format(afterSales.getCreateTime()));
                    request.getRequestDispatcher("/aftersalesadmin/editaftersale.jsp").forward(request, response);
                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "售后订单不存在");
                }
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "售后订单ID格式错误");
            }

        } else if ("delete".equals(action)) {
            // 删除售后订单
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                if (afterSalesService.deleteAfterSales(id)) {
                    response.sendRedirect(request.getContextPath() + "/afterSalesAdmin?action=list");
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "删除失败");
                }
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "售后订单ID格式错误");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out=response.getWriter();
        String action = request.getParameter("action");
        if ("add".equals(action)) {
            // 添加售后订单
            try {
                AfterSalesAdmin afterSales = new AfterSalesAdmin();
                afterSales.setSaleOrderId(Integer.parseInt(request.getParameter("saleOrderId")));
                afterSales.setUserId(Integer.parseInt(request.getParameter("userId")));
                afterSales.setProblem(request.getParameter("problem"));
                afterSales.setStatus(Integer.parseInt(request.getParameter("status")));
                afterSales.setCreateTime(sdf.parse(request.getParameter("createTime")));

                if (afterSalesService.addAfterSales(afterSales)) {
                    response.sendRedirect(request.getContextPath() + "/afterSalesAdmin?action=list");
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "添加失败");
                }
            } catch (NumberFormatException | ParseException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "参数格式错误: " + e.getMessage());
            }

        } else if ("update".equals(action)) {
            // 更新售后订单
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                if (afterSalesService.getAfterSalesById(id) == null) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "售后订单不存在");
                    return;
                }

                AfterSalesAdmin afterSales = new AfterSalesAdmin();
                afterSales.setId(id);
                afterSales.setSaleOrderId(Integer.parseInt(request.getParameter("saleOrderId")));
                afterSales.setUserId(Integer.parseInt(request.getParameter("userId")));
                afterSales.setProblem(request.getParameter("problem"));
                afterSales.setStatus(Integer.parseInt(request.getParameter("status")));
                afterSales.setCreateTime(sdf.parse(request.getParameter("createTime")));

                if (afterSalesService.updateAfterSales(afterSales)) {
                    response.sendRedirect(request.getContextPath() + "/afterSalesAdmin?action=list");
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新失败");
                }
            } catch (NumberFormatException | ParseException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "参数格式错误: " + e.getMessage());
            }
        }
    }
}
